package com.wjm.databaseframework.ac;

import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.wjm.databaseframework.R;
import com.wjm.databaseframework.bean.Photo;
import com.wjm.databaseframework.bean.User;
import com.wjm.databaseframework.db.BaseDao;
import com.wjm.databaseframework.db.BaseDaoFactory;
import com.wjm.databaseframework.db.BaseDaoNewImpl;
import com.wjm.databaseframework.permission.PermissionUtils;
import com.wjm.databaseframework.sub_sqlite.BaseDaoSubFactory;
import com.wjm.databaseframework.sub_sqlite.PhotoDao;
import com.wjm.databaseframework.sub_sqlite.UserDao;
import com.wjm.databaseframework.update.UpdateManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//a
public class MainActivity extends AppCompatActivity {

    private static String TAG = "databaseframework-MainActivity";

    private Button btn_create_DB_Table;
    private Button btn_insert;
    private Button btn_update;
    private Button btn_delete;
    private Button btn_select;
    private Button btn_fk;
    private Button btn_fk_cur_insert_photo;
    private Button btn_fk_cur_insert_tb_user;
    private Button btn_db_update;
    private Button btn_db_update_ing;
    private int startPage = 0x111;
    private int requestCode0x01 = 0x01;
    private int requestCode0x02 = 0x02;
    private int requestCode0x03 = 0x03;
    private int requestCode0x04 = 0x04;
    private int requestCode0x05 = 0x05;
    private int requestCode0x06 = 0x06;
    private int requestCode0x07 = 0x07;
    private int requestCode0x08 = 0x08;
    private int requestCode0x09 = 0x09;
    private int requestCode0x10 = 0x10;
    private UserDao userDao;
    private UpdateManager updateManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        updateManager=new UpdateManager();
        findViewById();
        String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        twoPermissions(permissions, startPage);
    }

    private void findViewById() {
        btn_create_DB_Table = findViewById(R.id.btn_create_DB_Table);
        btn_create_DB_Table.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                twoPermissions(permissions, requestCode0x01);//要2个权限 相机 和 sdcard
            }
        });
        btn_insert = findViewById(R.id.btn_insert);
        btn_insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                twoPermissions(permissions, requestCode0x02);//要2个权限 相机 和 sdcard

            }
        });
        btn_update = findViewById(R.id.btn_update);
        btn_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                twoPermissions(permissions, requestCode0x03);//要2个权限 相机 和 sdcard

            }
        });
        btn_delete = findViewById(R.id.btn_delete);
        btn_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                twoPermissions(permissions, requestCode0x04);//要2个权限 相机 和 sdcard

            }
        });
        btn_select = findViewById(R.id.btn_select);
        btn_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                twoPermissions(permissions, requestCode0x05);//要2个权限 相机 和 sdcard

            }
        });
        btn_fk = findViewById(R.id.btn_fk);
        btn_fk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                twoPermissions(permissions, requestCode0x06);//要2个权限 相机 和 sdcard

            }
        });
        btn_fk_cur_insert_photo = findViewById(R.id.btn_fk_cur_insert_photo);
        btn_fk_cur_insert_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                twoPermissions(permissions, requestCode0x07);//要2个权限 相机 和 sdcard

            }
        });
        btn_fk_cur_insert_tb_user = findViewById(R.id.btn_fk_cur_insert_tb_user);
        btn_fk_cur_insert_tb_user.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                twoPermissions(permissions, requestCode0x08);//要2个权限 相机 和 sdcard

            }
        });
        btn_db_update = findViewById(R.id.btn_db_update);
        btn_db_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                twoPermissions(permissions, requestCode0x09);//要2个权限 相机 和 sdcard

            }
        });
        btn_db_update_ing = findViewById(R.id.btn_db_update_ing);
        btn_db_update_ing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                twoPermissions(permissions, requestCode0x10);//要2个权限 相机 和 sdcard

            }
        });


    }

    /**
     * 获取到权限，功能代码在些写，并要通过请求码区分业务功能是哪一个
     *
     * @param requestCode
     */
    private void delayEntryPage(int requestCode) {
        String text = "";
        if (requestCode0x01 == requestCode) {
            text = "权限都有了，执行业务一：上传头像";
            getBaseDao();
        } else if (requestCode0x02 == requestCode) {
            text = "权限都有了，执行业务二：上传视频";
            insert();
        } else if (requestCode0x03 == requestCode) {
            text = "权限都有了，执行业务二：上传视频";
            update();
        } else if (requestCode0x04 == requestCode) {
            text = "权限都有了，执行业务二：上传视频";
            delete();
        } else if (requestCode0x05 == requestCode) {
            text = "权限都有了，执行业务二：上传视频";
            select();
        } else if (requestCode0x06 == requestCode) {
            text = "权限都有了，执行业务二：上传视频";
            fk();
        } else if (requestCode0x07 == requestCode) {
            text = "权限都有了，执行业务二：上传视频";
            btn_fk_cur_insert_Photo();
        } else if (requestCode0x08 == requestCode) {
            text = "权限都有了，执行业务二：上传视频";
            btn_fk_cur_insert_User();
        } else if (requestCode0x09 == requestCode) {
            text = "权限都有了，执行业务二：上传视频";
            btn_db_update();
        } else if (requestCode0x10 == requestCode) {
            text = "权限都有了，执行业务二：上传视频";
            btn_db_update_ing();
        }

        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();

    }

    /**
     * 重点是掌握它的行为方式，思想，具体细节优化什么的要几万行代码才能完成
     */
    private void btn_db_update_ing() {

        updateManager.checkThisVersionTable(this);//先检查是否有更新环境
        updateManager.startUpdateDb(this);//开始更新
    }

    private void btn_db_update() {
        updateManager.saveVersionInfo(this, "V003");
    }

    private void btn_fk_cur_insert_User() {
        UserDao baseDao = BaseDaoSubFactory.getOurInstance().getSubDao(UserDao.class, User.class);
        baseDao.insert(new User(6, "abcd", "123"));
        Toast.makeText(this, "执行成功!", Toast.LENGTH_SHORT).show();
    }

    private void btn_fk_cur_insert_Photo() {
        Photo photo = new Photo();
        photo.setPath("data/data/my.jpg");
        photo.setTime(new Date().toString());

        PhotoDao photoDao = BaseDaoSubFactory.getOurInstance().getSubDao(PhotoDao.class, Photo.class);
        photoDao.insert(photo);
        Toast.makeText(this, "执行成功!", Toast.LENGTH_SHORT).show();
    }

    int i = 0;

    /**
     * 分库，实际上就是不同的数据没有关联，用分库各自访问各自的数据库文件中的数据
     * 这里insert操作实际就是分库中换账号登录更新除当前用户之外的其它用户的状态，用来区分状态为1的是当前登录的用户，再在后面通过当前用户分别创建不同的dao去创建各自的数据库文件，达到分库的效果
     */
    private void fk() {
        userDao = BaseDaoFactory.getOurInstance().getBaseDao(UserDao.class, User.class);//分库，如果当前账号更换了通过一个状态为1的判断出当前用户是哪个

        //服务器传回的信息
        User user = new User();
        user.setName("张三" + (++i));
        user.setPassword("123456");
        user.setId(i);
        //数据插入
        userDao.insert(user);
        Toast.makeText(this, "执行成功!", Toast.LENGTH_SHORT).show();
    }

    /**
     * 要多个权限
     */
    private void twoPermissions(String[] permissions, int requestCode) {

        /**
         * 判断哪些权限未授予
         */
        List<String> permissionList = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permissions[i]);
            }
        }

        /**
         * 判断是否为空
         */
        if (permissionList.isEmpty()) {//未授予的权限为空，表示都授予了
            delayEntryPage(requestCode);
        } else {//请求权限方法
            String[] permissionsArr = permissionList.toArray(new String[permissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(this, permissionsArr, requestCode);
        }
    }


    private void select() {
        BaseDaoNewImpl baseDao = BaseDaoFactory.getOurInstance().getBaseDao(BaseDaoNewImpl.class, User.class);
        User where = new User();
        where.setName("abcd");
        List<User> list = baseDao.query(where);
        Log.i(TAG, "listsize=" + list.size());
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i).toString() + " i=" + i);
            System.out.println("==>" + i);
        }
    }

    /**
     * BaseDao<User> baseDao = BaseDaoFactory.getOurInstance().getBaseDao(User.class);//自动创建数据库与建表
     */
    private void getBaseDao() {
        BaseDao<User> baseDao = BaseDaoFactory.getOurInstance().getBaseDao(User.class);//自动建表
        Log.d(TAG, "执行成功");

    }

    /**
     * 插入数据
     */
    private void insert() {
        BaseDao<User> baseDao = BaseDaoFactory.getOurInstance().getBaseDao(User.class);//自动建表
        baseDao.insert(new User(1, "a", "123456"));
        Log.d(TAG, "插入数据 执行成功");
    }

    /**
     * 插入数据
     */
    private void update() {
        BaseDaoNewImpl baseDao = BaseDaoFactory.getOurInstance().getBaseDao(BaseDaoNewImpl.class, User.class);
        //update tb_user where name='jett' set password='1111'
        User user = new User();
        user.setName("abcd");
        User where = new User();
        where.setId(1);
        baseDao.update(user, where);
        Toast.makeText(this, "执行成功!", Toast.LENGTH_SHORT).show();
    }

    /**
     * 插入数据
     */
    private void delete() {
        BaseDaoNewImpl baseDao = BaseDaoFactory.getOurInstance().getBaseDao(BaseDaoNewImpl.class, User.class);
        //update tb_user where name='jett' set password='1111'
        User where = new User();
        where.setId(1);
        baseDao.delete(where);
        Toast.makeText(this, "执行成功!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (startPage == requestCode || requestCode0x01 == requestCode || requestCode0x02 == requestCode) {//456
            List<String> permissionList = new ArrayList<>();
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {//没获取到多个权限中的指定权限
                    //判断是否勾选禁止后不再询问
                    boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i]);
                    if (showRequestPermission) {//不是 再去重新申请
//                        twoPermissions();//重新申请权限
                        return;
                    } else {//是的 要去打开设置界面
                        permissionList.add(permissions[i]);
                    }
                }
            }
            //判断是禁止了权限弹框就弹出提示，手动跳设置开权限才能用
            if (null != permissionList && permissionList.size() > 0) {
                String sbStr = PermissionUtils.getPermissionStr(permissionList);
                AlertDialog dialog = new AlertDialog.Builder(this).setMessage("该功能需要开启 " + sbStr + " 权限，不开启无法正常工作！")
                        .setPositiveButton("知道了，去设置中手动开启 ", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                PermissionUtils.startSettActivity(MainActivity.this);
                            }
                        })
                        .create();
                dialog.show();
            } else {
                //权限都获取到了，可以去做操作了
                delayEntryPage(requestCode);
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
